package cn.flightcloud.auth.config.spring.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import cn.flightcloud.auth.config.spring.security.service.SimpleUserDetailsService;

@EnableWebSecurity
@Configuration
@Order(1)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

	@Bean
	@Override
	public UserDetailsService userDetailsServiceBean() throws Exception {
		return new SimpleUserDetailsService();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		// 忽略css.jq.img等文件
		web.ignoring().antMatchers("/**.html", "/**.css", "/img/**", "/**.js", "/third-party/**");

//		web.ignoring().antMatchers("/webjars/**", "/resources/**");
	}

    @Override
    protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/login", "/css/**", "/image/*").permitAll()//
				.antMatchers("/**").authenticated().and().formLogin().loginPage("/login")// 设置登录页面
				.defaultSuccessUrl("/")// 设置默认登录成功跳转页面
				.failureUrl("/login?error").permitAll()// 设置登录失败的页面
				.and().logout().and().userDetailsService(userDetailsServiceBean());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceBean())
        .passwordEncoder(passwordEncoder());
    }
}
